package com.yyfax.ph.personal.authority.bankcard.presenter;

import android.text.TextUtils;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import com.yyfax.infrastructure.secure.RSA;
import com.yyfax.infrastructure.statistics.StatService;
import com.yyfax.ph.StatIDSet;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.personal.authority.RSAPresenter;
import com.yyfax.ph.personal.authority.bankcard.model.GetOwnedBankModel;
import com.yyfax.ph.common.GlobalVariableConfig;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * P: 根据银行卡号判断开户银行
 * Created by ying_he on 2017/6/12.<br>
 * Copyright  2017 www.yylending.com. All Rights Reserved.<br><br>
 */

public class GetOwnedBankPresenter extends RSAPresenter<GetOwnedBankModel, GetOwnedBankPresenter.View> {

	public static class Generator implements PresenterFactory<GetOwnedBankPresenter> {
		@Override
		public GetOwnedBankPresenter create() {
			return new GetOwnedBankPresenter();
		}
	}

	public interface View extends IView {
		void getOwnedBankSuccess(GetOwnedBankModel.OwnedBank bank);//成功获取到支持银行

		void notSupportBank();//不支持银行

		void isCreditCard();//为信用卡

		void getOwnedBankFailure(String tips);//获取失败，银行卡号错误
	}

	private View mView;
	private static final String isDebitCard = "1";

	@Override
	public void attach(View view) {
		mView = view;
		mModel = new GetOwnedBankModel();
		EventAgent.register(this);
	}

	@Override
	public void detach() {
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	public void getOwnedBank(String bankCard) {
		GetOwnedBankModel.RequestParams params = new GetOwnedBankModel.RequestParams();
		params.cardId = bankCard;
		execute(params, FUNCTIONAL_CODE, false);
	}

	@Override
	public Object getRSAParams(Object params, int functionalCode) {
		GetOwnedBankModel.RequestParams card = (GetOwnedBankModel.RequestParams) params;
		String keyRSA = GlobalVariableConfig.getKeyRSA();
		card.cardId = RSA.encryptByPublicKey(card.cardId, keyRSA);
		return card;
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void getOwnedBankResult(GetOwnedBankModel.OwnedBankResult result) {
		StatService.onEventFirstKeyAttribute(YJPH.getInstance(), StatIDSet.EVENT_ID_E028, result.getStatus());
		if (isResponseSuccess(result)) {
			if (!isDebitCard.equals(result.getContent().cardType))//是信用卡
				mView.isCreditCard();
			else {
				if (TextUtils.isEmpty(result.getContent().bankCode) || TextUtils.isEmpty(result.getContent().bankDescription))
					mView.notSupportBank();//不支持银行
				else
					mView.getOwnedBankSuccess(result.getContent());//成功获取到支持银行
			}
		} else {
			mView.getOwnedBankFailure(TextUtils.isEmpty(result.getMsg()) ? "获取银行失败" : result.getMsg());//获取失败，银行卡号错误
		}
	}
}
